﻿using EasyCore.UnifyResult;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.DataValidation
{
    public class DataValidationFilter : IAsyncActionFilter, IOrderedFilter
    {
        public int Order => -1000;
        private ApiBehaviorOptions _options { get; set; }

        public DataValidationFilter(IOptions<ApiBehaviorOptions> options)
        {
            _options = options.Value; //api接口配置
        }


        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //web socket 请求处理
            if (context.HttpContext.WebSockets.IsWebSocketRequest)
            {
                await next();
                return;
            }

            //获得控制器基本信息
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;//控制器基本信息
            var method = actionDescriptor.MethodInfo; //行为方法的基本信息
            if (actionDescriptor.Parameters.Count == 0) {
                //不存在参数时，正常处理逻辑
                await next();
                return;
            }

            //采用.net core 参数验证规则
            if (!_options.SuppressModelStateInvalidFilter)
            {
                var modelState = context.ModelState; //.net core默认参数验证信息
                if (modelState.IsValid) {
                    await next();
                    return;                
                }    
                context.Result = _options.InvalidModelStateResponseFactory(context); //处理验证信息
                return;
            }

            //现系统采用的验证规则
            // 如果参数数量为 0 或贴了 [NonValidation] 特性 或所在类型贴了 [NonValidation] 特性或验证成功或已经设置了结果，则跳过验证
            var nonValidationAttributeType = typeof(NonValidationAttribute);
            if (method.IsDefined(nonValidationAttributeType, true) || method.DeclaringType.IsDefined(nonValidationAttributeType, true) )
            {
                await next();
                return;
            }

            //执行数据验证
            foreach (var item in actionDescriptor.Parameters) { 
              

               

            
            
            
            }






  

 /*
            //处理验证信息

            //模型绑定信息
            var validationResults = modelState.Where(u => modelState[u.Key].ValidationState == ModelValidationState.Invalid)
        .ToDictionary(u => u.Key, u => modelState[u.Key].Errors.Select(c => c.ErrorMessage).ToArray());
            context.Result = new JsonResult(new RESTfulApiResult((int)EasyAdminStatusCodes.ParametersError, msg: "提交的数据存在错误", errors: validationResults));

            */
        }
    }
}
